package routers

import (
	"software/global"

	"github.com/gin-gonic/gin"
)

type RouterGroup struct {
	*gin.RouterGroup
}

func InitRouter() *gin.Engine {
	gin.SetMode(global.Config.System.Env)
	router := gin.Default()

	// 添加CORS中间件
	router.Use(func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "http://localhost:8080") // 允许的前端地址
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization")
		c.Header("Access-Control-Allow-Credentials", "true") // 如果需要携带cookie，设置为true

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204) // 处理预检请求
			return
		}

		c.Next()
	})

	apiRouterGroup := router.Group("api")
	routerGroupApp := RouterGroup{apiRouterGroup}
	//系统配置api
	routerGroupApp.SettingsRouter(router)
	routerGroupApp.AdminsRouter(router)
	routerGroupApp.UsersRouter(router)
	routerGroupApp.PhotosRouter(router)
	routerGroupApp.PostsRouter(router)
	routerGroupApp.CommentsRouter(router)
	return router
}
